<template>
  <div style="position: relative">
    <el-drawer v-model="props.brandDrawer" title="轮播图" :before-close="handleBrandClose" size="60%">
      <el-button type="primary" @click="addList" style="margin: 10px 0">新增</el-button>

      <el-table :data="tableData">
        <el-table-column prop="image" label="图片" align="center" width="250">
          <template #default="scope">
            <div @click="testInput(scope.$index)">
              <ImageUpload :limit="1" :isShowTip="false" v-model="scope.row.newImage" @baseUrl="handleImageList">
              </ImageUpload>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sysTagType" label="标签类型" align="center" width="150">
          <template #default="scope">
            <el-select v-model="scope.row.sysTagType" placeholder="请选择" style="width: 100px"
              @change="handleMenuTypeChange(scope.$index, scope.row.sysTagType)">
              <el-option v-for="dict in sys_tag_type" :key="dict.value" :label="dict.label" :value="dict.value"
                :disabled="disabledOptions.includes(dict.value)" />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column prop="url" label="链接">
          <template #default="scope">
            <el-space spacer=" ">
              <el-text class="mb8">
                {{ scope.row.menuTypeAssociationIdFrom?.name }}
              </el-text>
            </el-space>
            <el-input v-model.trim="scope.row.url" placeholder="请输入" :disabled="true
              " v-if="scope.row.sysTagType != 'link'">
              <template #append v-if="newSelect.includes(scope.row.sysTagType)"><el-button type="primary" size="small"
                  @click="addListId(scope.$index, scope.row)">新增</el-button></template>
            </el-input>




            <el-input v-model.trim="scope.row.url" placeholder="请输入" v-else />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template #default="scope">
            <div style="display: flex;flex-direction: column;align-items: center;cursor: pointer;gap: 10px;">
              <el-text v-for="item in richText" :key="item.id" link :type="item.type"
                @click="handleRichText(item.id, scope.row, scope.$index)">{{ item.name }}</el-text>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <WebRichText @handleRichClose="handleRichClose" :publicFrom="publicFrom" :RichVisible="RichVisible"></WebRichText>

      <PublicList :from="publicFrom?.menuTypeAssociationIdFrom" :newType="typeList" @publicListSure="publicListSure"
        @publicListCancel="publicListCancel" :showList="showList" :websiteId="props.websiteId"
        :languageId="props.languageId">
      </PublicList>
      <WebPreview :PreviewVisible="PreviewVisible" :publicFrom="publicFrom" @handlePreviewClose="handlePreviewClose">
      </WebPreview>
    </el-drawer>
  </div>
</template>
<script setup>
import { ref, defineProps, defineEmits, watch, reactive, onMounted } from "vue";
import { slugify } from "transliteration";
import PublicList from "../components/publicList.vue";
import WebRichText from "../web/webRichText.vue";
import WebPreview from "../web/webPreview.vue";

const emits = defineEmits(["handleBrandClose"]);
const { proxy } = getCurrentInstance();
const { sys_tag_type } = proxy.useDict("sys_tag_type");
const tableData = ref([]);
const tableIndex = ref(0);//获取的下标
const basicDate = ref({});//基础信息数据
const sys_language_type = ref([]);//语言列表数据
const publicFrom = ref({});//获取公共的数据
const RichVisible = ref(false)
const PreviewVisible = ref(false)

const siteProductSortList = ref([])//商品分类
const siteProductList = ref([])//商品
const articlesList = ref([])//文章
const brandList = ref([])//商品品牌

const showList = ref(false)//默认不显示，列表弹出框显示
const typeList = ref('')

// 禁止选择的项
const disabledOptions = ["text", "article", "account", "order", "wishlist"];
const newSelect = ["category", "product", "news_detail", "brand"];

const props = defineProps({
  brandDrawer: {
    type: Boolean,
    default: false,
  },
  // 传值数据对象
  listItem: {
    type: Object,
    default: {},
  },
  websiteId: {
    type: String || Number,
    default: "",
  },
  languageId: {
    type: String || Number,
    default: null,
  }
});
const searchFrom = ref({
  pageNum: 1,
  pageSize: 999,
  param: {
    websiteId: Number(props.websiteId), //网站id

    moduleId: null, //模块id
    moduleType: "Banner",
  },
});
watch(
  () => props.brandDrawer,
  () => {
    if (!props.brandDrawer) return;
    tableData.value = [];
    getList();
  }
);
const getList = () => {
  searchFrom.value.param.moduleId = props.listItem.id;
  site.moduleline
    .sitewebsitemodulelineList({
      data: searchFrom.value,
    })
    .then((res) => {
      if (res.data?.length) {
        res.data = res.data.map((item) => {
          return {
            ...item,
            titleGroups: newLanguageList(item.moduleDescriptions),
            menuTypeAssociationIdFrom: menuTypeAssociationIdFrom(item),
            newImage: item.host,
          };
        });
      }
      tableData.value = res.data;
    });
};
const handleRichText = (id, row, index) => {
  tableIndex.value = index;
  publicFrom.value = row;
  if (id === 1) {//完成
    handleDone(row)
  } else if (id === 2) {//预览效果
    if (!row.newImage) return proxy.$modal.msgError("请上传照片");



    PreviewVisible.value = true
  } else if (id === 3) {//添加富文本
    RichVisible.value = true
  } else {//删除
    handleDelete(index, row)
  }
}
const handleDone = (rowItem) => {
  if (!rowItem.newImage) return proxy.$modal.msgError("请上传照片");
  //完成
  if (rowItem.id) {
    // let from = {
    //   image: rowItem.image,
    //   sysTagType: rowItem.sysTagType,
    //   url: `${handleLink(rowItem.sysTagType)}${rowItem.url}`,
    // };
    // console.log(from.url);
    // return
    // 完成编辑接口
    site.moduleline
      .sitewebsitemodulelineUpdate({
        pathParams: {
          id: rowItem.id,
        },
        data: rowItem,
      })
      .then((res) => {
        if (res.code === 200) {
          tableData.value = []
          getList();
          proxy.$message.success("编辑成功");
        }
      });
  } else {
    // 新增接口
    console.log(rowItem);
    site.moduleline
      .sitewebsitemodulelineAdd({
        data: rowItem,
      })
      .then((res) => {
        if (res.code === 200) {
          tableData.value = []
          getList();
          proxy.$message.success("新增成功");
        }
      });
  }
};

// 删除
const handleDelete = (index, rowItem) => {
  if (rowItem.id) {
    deleteItem(rowItem);
  } else {
    tableData.value.splice(index, 1);
  }
};
const handleBrandClose = () => {
  emits("handleBrandClose");
};

const handleImageList = (val) => {
  tableData.value[tableIndex.value].image = val.url;
};
const testInput = (index) => {
  tableIndex.value = index;
};
// 新增
const addList = () => {
  tableData.value.push({
    moduleId: props.listItem.id,
    image: "",
    url: "",
    newImage: "",
    recordValue: null,//选择的id
    sysTagType: '',
    menuTypeAssociationIdFrom: {},
    titleGroups: [
      // languageId
      // name
      // description
    ]
  });
  basicDate.value.languageIds.forEach(code => {
    tableData.value[tableData.value.length - 1].titleGroups.push({
      languageId: code,
      languageIdName: sys_language_type.value.find(e => e.id === code)?.description,
      name: '后端说随便填写',
      description: "",
    });
  })

  // console.log(basicDate.value, '基础信息');
};
const newLanguageList = (list) => {
  let newList = []
  newList = list.map(code => {
    return {
      languageId: code.languageId,
      languageIdName: sys_language_type.value.find(e => e.id === code.languageId)?.description,
      name: code.name,
      description: code.description,
    }
  })
  return newList
}
const deleteItem = (row) => {
  var newArray = [];
  newArray.push(row.id);
  proxy.$modal.confirm("是否确认删除此数据项？").then(() => {
    site.moduleline
      .sitewebsitemodulelineDeletebatch({
        data: {
          ids: newArray,
          moduleId: props.listItem.id,
        },
      })
      .then((res) => {
        if (res.code === 200) {
          getList();
          proxy.$message.success("删除成功");
        }
      });
  });
};
const handleLink = (sysTagType) => {
  return sys_tag_type.value.find(e => e.value === sysTagType)?.elTagClass
}
const handleMenuTypeChange = (index, val) => {
  console.log(index, val, '[[[[[]]]]]');
  tableData.value[index].menuTypeAssociationIdFrom = {}
  tableData.value[index].recordValue = null

  // 商品类别===文章详情===商品===品牌详情：需要获取对应的列表的id
  // 其他的选项获取的的value值给url
  const { elTagClass, value } = sys_tag_type.value.find(e => e.value === val)
  tableData.value[index].url = ''
  if (val === 'news') {//文章
    tableData.value[index].url = `${elTagClass}`
  } else if (val === 'brand_list') {
    tableData.value[index].url = `${elTagClass}`
  }


  // if (val === "category") {//商品分类====分类名称-c-分类id，树形结构
  //   const { name, id } = findNodeById(publicList.value, e)
  //   tableData.value[index].url = `/${value}/${formatUrl(name)}${elTagClass}${id}`
  // } else if (val === "product") {//商品=== 商品名称-p-商品id
  //   const { name, id } = siteProductList.value.find(item => item.id === e)
  //   tableData.value[index].url = `/${value}/${formatUrl(name)}${elTagClass}${id}`
  // } else if (val === "news_detail") {//文章详情===博客名称-n-博客id
  //   const { name, id } = articlesList.value.find(item => item.id === e)
  //   tableData.value[index].url = `/${value}/${formatUrl(name)}${elTagClass}${id}`
  // } else if (val === "brand") {//品牌详情:  品牌名称-b-品牌id
  //   const { name, id } = brandList.value.find(item => item.id === e)
  //   tableData.value[index].url = `/${value}/${formatUrl(name)}${elTagClass}${id}`
  // }
}
const findNodeById = (tree, id) => {
  for (let node of tree) {
    if (node.id === id) {
      return node; // 找到目标节点
    }
    if (node.children) {
      let found = findNodeById(node.children, id);
      if (found) return found; // 递归查找子节点
    }
  }
  return null; // 没找到
}
function formatUrl(input) {
  return slugify(input, { separator: '-' });
}
const addListId = (index, row) => {
  tableIndex.value = index
  publicFrom.value = row
  showList.value = true
  typeList.value = row.sysTagType
  console.log(row, '[[[[]]]]');
}
const publicListCancel = () => {
  showList.value = false
}
const handlePreviewClose = () => {
  PreviewVisible.value = false
  publicFrom.value = {}
}
const publicListSure = (row) => {
  tableData.value[tableIndex.value].recordValue = row.id
  tableData.value[tableIndex.value].menuTypeAssociationIdFrom = row
  showList.value = false
  console.log(tableData.value);
  handleRichType()
}
const menuTypeAssociationIdFrom = (item) => {
  let recordValueInt = Number(item.recordValue)

  if (item.sysTagType === "category") {//商品分类====
    let from

    from = findNodeById(siteProductSortList.value, recordValueInt)
    return {
      name: from?.name,
      id: from?.id
    }
  } else if (item.sysTagType === "product") {//商品
    let from

    from = siteProductList.value.find(item => item.id === recordValueInt)
    return {
      name: from?.name,
      id: from?.id
    }

  } else if (item.sysTagType === "news_detail") {
    let from = articlesList.value.find(item => item.id === recordValueInt)
    return {
      name: from?.name,
      id: from?.id
    }

  } else if (item.sysTagType === "brand") {
    let from = brandList.value.find(item => item.id === recordValueInt)
    // const { name, id } = brandList.value.find(item => item.id === Number(item.recordValue))
    return {
      name: from?.name,
      id: from?.id
    }
  }
  return {

  }
}
const handleRichType = () => {
  tableData.value[tableIndex.value].url = ''
  let { sysTagType, recordValue } = tableData.value[tableIndex.value]
  const { elTagClass, value } = sys_tag_type.value.find(
    (e) => e.value === sysTagType
  )

  if (sysTagType === "category") {//商品分类====分类名称-c-分类id，树形结构
    const { name, id } = findNodeById(siteProductSortList.value, recordValue)
    tableData.value[tableIndex.value].url = `/${value}/${formatUrl(name)}${elTagClass}${id}`
  } else if (sysTagType === "product") {//商品=== 商品名称-p-商品id
    const { name, id } = siteProductList.value.find(item => item.id === recordValue)
    tableData.value[tableIndex.value].url = `/${value}/${formatUrl(name)}${elTagClass}${id}`
  } else if (sysTagType === "news_detail") {//文章详情===博客名称-n-博客id
    const { name, id } = articlesList.value.find(item => item.id === recordValue)
    tableData.value[tableIndex.value].url = `/${value}/${formatUrl(name)}${elTagClass}${id}`
  } else if (sysTagType === "brand") {//品牌详情:  品牌名称-b-品牌id
    const { name, id } = brandList.value.find(item => item.id === recordValue)
    tableData.value[tableIndex.value].url = `/${value}/${formatUrl(name)}${elTagClass}${id}`
  }
}

const handleRichClose = (rowList) => {
  tableData.value[tableIndex.value].titleGroups = rowList
  RichVisible.value = false
}


onMounted(() => {
  getDateList()
  getBasics(); //获取基础信息
})
const getBasics = () => {// 获取基础信息
  site.general
    .sitewebsiteGetbyid({
      pathParams: {
        id: Number(props.websiteId),
      },
    })
    .then((res) => {
      basicDate.value = res.data
    });
  product.language.languageList().then((res) => {  // 获取语言列表
    sys_language_type.value = res.data;
  });
}
const getDateList = () => {
  // 查询参数
  var from = {
    pageNum: 1,
    pageSize: 999,
    param: {
      websiteId: Number(props.websiteId),
      languageId: Number(props.languageId),
      fatherId: 0,
    },
  };
  site.general
    .sitecategoryList({
      data: from,
    })
    .then((res) => {//商品分类
      siteProductSortList.value = res.data;
      // console.log( siteProductSortList.value,'商品分类');
    });
  site.general
    .sitewebsiteproductList({
      data: {
        pageNum: 1,
        pageSize: 999,
        param: {
          websiteId: Number(props.websiteId),
        },
      },
    })
    .then((res) => {//商品
      siteProductList.value = res.data
      // console.log(siteProductList.value, '商品');
    });

  site.general
    .sitearticleList({
      data: {
        pageNum: 1,
        pageSize: 999,
        param: {
          websiteId: Number(props.websiteId),
        },
      },
    })
    .then((res) => {//文章
      if (res.code === 200 && res.data?.length) {
        res.data = res.data.map(e => {
          return {
            ...e,
            name: e.title
          }
        })
      }
      articlesList.value = res.data
    })

  site.general
    .sitewebsitebrandList({
      data: {
        pageNum: 1,
        pageSize: 999,
        param: {
          websiteId: Number(props.websiteId),
        },
      },
    })
    .then((res) => {//商品品牌
      if (res.code === 200 && res.data?.length) {
        res.data = res.data.map(e => {
          return {
            ...e,
            name: e.commonName
          }
        })
      }
      brandList.value = res.data;
      // console.log(brandList.value, '商品品牌');
    });
}



const richText = reactive([
  {
    name: '添加文本',
    id: 3,
    type: 'primary'
  },
  {
    name: '预览效果',
    id: 2,
    type: 'primary'
  },
  {
    name: '完成',
    id: 1,
    type: 'primary'
  }, {
    name: '删除',
    id: 0,
    type: 'danger'
  }


])
</script>
<style lang="scss" scoped>
.full-width {
  width: 148px;
}

.handle_box {
  position: absolute;
  bottom: 5%;
  display: flex;
  justify-content: space-around;
  width: 100%;

  >button {
    width: 200px;
  }
}

:deep .el-upload--picture-card {
  height: 100px;
}

:deep .el-upload-list--picture-card .el-upload-list__item {
  height: 100px;
}
</style>